package com.welike.shibo.job;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.welike.shibo.service.RedisService;
import com.welike.shibo.utils.QiNiuUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Date;

import static com.welike.shibo.utils.Constants.REDIS_UPLOAD_KEY;

/**
 * @author fangyu
 * @version v1.0.0
 * @since 2019/12/4 9:52 上午
 */
@Slf4j
@Component
public class UploadJob {

    public static final String FAIL_KEY = REDIS_UPLOAD_KEY + "fail_task";


    @Autowired
    private RedisService redisService;

    @Autowired
    private QiNiuUtil qiNiuUtil;

    /**
     * 上传的定时任务，每3秒执行一次
     */
    @Scheduled(fixedRate = 3000)
    private void uploadTask(){
        String key = REDIS_UPLOAD_KEY + "task";
        String value = redisService.rpop(key);
        if (value !=null) {
            log.info("定时任务 ===> 正在执行上传任务: {}", value);
            JSONObject rs = JSON.parseObject(value);
            String name = rs.getString("name");
            String path = rs.getString("path");
            try {
                qiNiuUtil.upload(path, name);
            } catch (IOException e){
                log.error("上传失败 ==> {}", e.getMessage());
                JSONObject failValue = new JSONObject();
                failValue.put("name", name);
                failValue.put("path", path);
                redisService.lpush(FAIL_KEY, failValue.toJSONString());
            }
        } else {
            log.info("{}: 无上传任务", new Date());
        }
    }

    /**
     * 上传失败的定时任务，每60秒执行一次
     */
    @Scheduled(fixedRate = 180000)
    private void uploadFailTask(){
        String value = redisService.rpop(FAIL_KEY);
        if (value !=null) {
            JSONObject rs = JSON.parseObject(value);
            String name = rs.getString("name");
            String path = rs.getString("path");
            try {
                qiNiuUtil.upload(path, name);
            }catch (Exception e){
                log.error("上传失败 ==> {}", e.getMessage());
                JSONObject failValue = new JSONObject();
                failValue.put("name", name);
                failValue.put("path", path);
                redisService.lpush(FAIL_KEY, failValue.toJSONString());            }
        } else {
            log.info("{}: 无上传失败的任务", new Date());
        }
    }
}
